added samples
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2008 / CSHeapCorruption / Program.cs
blob27b91a1e5426dd04dc4ffe9e06ca65ff216637dd
1 /******************************** Module Header ********************************\
2 Module Name: Program.cs
3 Project: CSHeapCorruption
4 Copyright (c) Microsoft Corporation.
8 This source is subject to the Microsoft Public License.
9 See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
10 All other rights reserved.
12 THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
13 EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
14 OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
15 \*******************************************************************************/
17 using System;
18 using System.Runtime.InteropServices;
21 namespace CSHeapCorruption
23 class Program
25 static void Main(string[] args)
27 if (args.Length > 0 && (args[0].StartsWith("-") || args[0].StartsWith("/")))
29 string cmd = args[0].Substring(1);
31 if (String.Compare(cmd, "o", true) == 0)
33 // Overrun the managed GC heap.
34 OverrunManagedGCHeap();
36 else if (String.Compare(cmd, "h", true) == 0)
38 // Mismatch the heap handle.
39 MismatchHeapHandle();
41 else
43 PrintInstructions();
46 else
48 PrintInstructions();
51 Console.Write("Press ENTER to exit ...");
52 Console.ReadLine();
56 static void PrintInstructions()
58 Console.WriteLine("CSHeapCorruption Instructions:");
59 Console.WriteLine("-o Overrun the managed GC heap");
60 Console.WriteLine("-h Mismatch the heap handle");
64 #region Managed GC Heap Overrun
66 /// <summary>
67 ///
68 /// </summary>
69 static void OverrunManagedGCHeap()
71 int[] buffer = new int[50];
72 for (int i = 0; i < buffer.Length; i++)
74 buffer[i] = 0xFF;
77 Console.Write("Press ENTER to overrun GC heap ...");
78 Console.ReadLine();
80 InitializeBuffer(buffer, buffer.Length);
82 //GC.Collect();
85 [DllImport("CSHeapCorruption.NativeDll.dll", CharSet = CharSet.Unicode)]
86 static extern void InitializeBuffer(int[] buffer, int size);
88 #endregion
91 #region Heap Handle Mismatch
93 /// <summary>
94 ///
95 /// </summary>
96 static void MismatchHeapHandle()
98 // Allocate a block of memory. The native function AllocateMemory
99 // allocates the memory on the CRT heap.
100 IntPtr pMem = AllocateMemory(50);
102 Console.Write("Press ENTER to mismatch heap handle ...");
103 Console.ReadLine();
105 // Free the allocated memory on the wrong process heap.
106 Marshal.FreeHGlobal(pMem);
109 [DllImport("CSHeapCorruption.NativeDll.dll", CharSet = CharSet.Unicode)]
110 static extern IntPtr AllocateMemory(int bytes);
112 #endregion